package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.RedisConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.admin.DishMapper;
import com.sky.mapper.admin.FlavorsMapper;
import com.sky.mapper.admin.SetmealMapper;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;

/**
 * 菜品业务层实现类
 */
@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private FlavorsMapper flavorsMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 新增菜品
     *
     * @param dishDTO
     */
    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        dishMapper.insert(dish);
        // 增加菜品口味
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (flavorList != null && flavorList.size() > 0) {

            // 主键返回
            flavorList.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            flavorsMapper.insert(flavorList);
        }

        // 清空缓存
        redisTemplate.delete(RedisConstant.DISH_CATEGORY + dishDTO.getCategoryId());
    }

    /**
     * 菜品分页
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishs = dishMapper.list(dishPageQueryDTO);
        return new PageResult(dishs.getTotal(), dishs.getResult());
    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDish(List<Long> ids) {
        // 判断菜品在售才能删除
        Integer queryStatus = dishMapper.queryStatus(ids, StatusConstant.ENABLE);
        if (queryStatus > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        // 判断套餐不含菜品才能删除
        Integer findDishes = setmealMapper.findDishes(ids);
        if (findDishes > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 都没有进行删除菜品
        dishMapper.delete(ids);
        // 删除菜品的口味
        flavorsMapper.delete(ids);
        // 清空缓存
        cleanCahe();
    }



    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    @Override
    public DishVO findById(Long id) {
        return dishMapper.seleteById(id);
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     */
    @Override
    public void updateDish(DishDTO dishDTO) {
        // 修改菜品信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        // 判断口味,是否为空
        List<DishFlavor> flavorList = dishDTO.getFlavors();
        if (flavorList == null || flavorList.size() == 0) {
            return;
        }
        // 口味不为空,删除原来口味,添加新口味
        List<Long> ids = Arrays.asList(dish.getId());
        flavorsMapper.delete(ids);
        flavorsMapper.insert(flavorList);

        // 清空缓存
        cleanCahe();
    }

    /**
     * 根据分类id查菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> categoryById(Long categoryId) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<Dish> dishes = (List<Dish>) valueOperations.get(RedisConstant.DISH_CATEGORY + categoryId);
        // 查询缓存中是否存在
        if (dishes == null || dishes.size() == 0) {
            dishes = dishMapper.seleteByCategoryId(categoryId);
            // 存入缓存中
            valueOperations.set(RedisConstant.DISH_CATEGORY + categoryId, dishes);
        }
        return dishes;
    }

    /**
     * 修改菜品状态
     *
     * @param status
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDishStatus(Integer status, Long id) {
        // 菜品停售，则包含菜品的套餐同时停售
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            // 检查套餐是否包含要停售的菜品
            List<Long> disabledDishSetmealId = setmealMapper.includesDisabledDish(id);
            // 获得包含该菜品的套餐id
            if (!CollectionUtils.isEmpty(disabledDishSetmealId)) {
                disabledDishSetmealId.forEach(setmealId -> setmealMapper.updateSetmealStatus(StatusConstant.DISABLE, setmealId));
            }
        }
        dishMapper.updateDishStatus(status, id);

        // 清空缓存
        cleanCahe();
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listByDish(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = flavorsMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    private void cleanCahe() {
        Set keys = redisTemplate.keys(RedisConstant.DISH_CATEGORY + "*");
        redisTemplate.delete(keys);
    }

}
